<?php

require_once(APP.'libs'.DS.'system_properties.php');
require_once(APP.'libs'.DS.'my_app_model.php');

class Product extends MyAppModel
{
	var $name='Product';
	var $validate = array();

	function getStatic($type) {
	    $type = ($type=='zhuan')?'zhuan':'huan';
	    $ret = array('product_total'=>0, 'luck_total'=>0);
	    $table = ($type=='zhuan')?'g_products':'g_changes';
	    $data = $this->query('select count(1) as count from '.$table);
	    if (!empty($data[0][0]['count'])){
	        $ret['product_total'] = $data[0][0]['count'];
	    }
	    $data = $this->query("select count(1) as count from g_lucks where how_get='$type'");
	    if (!empty($data[0][0]['count'])){
	        $ret['luck_total'] = $data[0][0]['count'];
	    }
	    return $ret;
	}
	//获取产品信息
	function getProductInfo($id){
		$id = intval($id);
		$data = $this->query("select * from  g_products u where g_id=$id and in_list = 1 limit 1");
		if (!empty($data[0]['u'])){
			return $data[0]['u'];
		}else {
			return array();
		}

	}
	
	function getChangeInfo($id){
		$id = intval($id);
		$data = $this->query("select * from  g_changes u where g_id=$id and in_list = 1 limit 1");
		if (!empty($data[0]['u'])){
			return $data[0]['u'];
		}else {
			return array();
		}
		
	}
	function getProductInfoForBuildHTML($id){
		$id = intval($id);
		$xn_user_id=$_SESSION['xn_user_id'];
		$inlist = '';//' and in_list = 1 ';
		if ($xn_user_id == SystemProperties::$admin_uid) {
		      $inlist = '';
		}		
    	$data = $this->query("select * from  g_products p where g_id=$id $inlist limit 1");
		return $data;
	}
	
	function getChangeInfoForBuildHTML($id){
		$id = intval($id);
		$xn_user_id=$_SESSION['xn_user_id'];
		$inlist = '';//' and in_list = 1 ';
		if ($xn_user_id == SystemProperties::$admin_uid) {
		      $inlist = '';
		}
		$data = $this->query("select * from  g_changes p where g_id=$id $inlist limit 1");
		return $data;
	}
	
	function getProductFreeList($prenum,$number,$cat=0,&$total){
		$prenum = intval($prenum);
		$number = intval($number);
		$cat = intval($cat);
		$data = $this->query("select SQL_CALC_FOUND_ROWS i.* from g_products i  where in_list = 1 and g_cat=$cat and g_number>0 order by g_hot desc,popularity  desc limit $prenum,$number ");
	    $t = $this->query("SELECT FOUND_ROWS() as n");//getNumRows();
	    $total = $t[0][0]['n'];
		return $data;
	}
	function getProductList($prenum,$number){
		$prenum = intval($prenum);
		$number = intval($number);
		$data = $this->query("select i.* from g_products i where g_price>0 and in_list = 1 order by g_hot desc,popularity  desc limit $prenum,$number ");
		return $data;
	}
	function getChangeProductList($prenum,$number){
		$prenum = intval($prenum);
		$number = intval($number);
		$data = $this->query("select i.* from g_changes i where in_list = 1 order by (g_number>0) desc ,g_order desc limit $prenum,$number ");
		return $data;
	}
	function getCoupon($pid, $uid) {
	    $pid = intval($pid);
	    $uid = intval($uid);
	    $sql = "select * from `g_coupon` where pid=$pid and uid = $uid";
	    $data = $this->query($sql);
	    
	    if (empty($data)) {
	        $sql = "update `g_coupon` set uid=$uid , time=now() where pid=$pid and uid=0 limit 1";
	        $this->query($sql);
    	    $sql = "select * from `g_coupon` where pid=$pid and uid = $uid and 1";
    	    $data = $this->query($sql);	        
	    }
	    if (!empty($data[0]['g_coupon']['code'])) {
	        return array(
	           'coupon' =>$data[0]['g_coupon']['code'],
	           'coupon_limit_time'=>date('Y-m-d H:i:s',strtotime($data[0]['g_coupon']['limit_time'])),
	        );
	        
	    } else {
	        return array();
	    }
	}
	function getApplyUsers($id, &$total) {
	    $id = intval($id);
	    $data = $this->query("SELECT SQL_CALC_FOUND_ROWS g_name,time,user_id as uid FROM `g_timesplit_logs` inner join g_users on `g_timesplit_logs`.user_id = g_users.g_id WHERE `product_id`={$id} and seqid>0 order by seqid desc limit 50");
	    $t = $this->query("SELECT FOUND_ROWS() as n");//getNumRows();
	    $total = $t[0][0]['n'];
	    if (empty($data)){
	        return array();
	    } else {
	       return $data;
	    }
	}
	function getOldProductList($start, $count, &$total) {
	    $start = intval($start);
	    $count = intval($count);
	    $data = $this->query("SELECT SQL_CALC_FOUND_ROWS i.* FROM `g_products` i where in_wangqi_list = 1 and (in_list = 0 or g_number=0) order by g_id desc limit $start,$count");
	    $t = $this->query("SELECT FOUND_ROWS() as n");//getNumRows();
	    $total = $t[0][0]['n'];
	    if (empty($data)){
	        return array();
	    } else {
	       return $data;
	    }	    
	}

	/*----- cy add, 2011-4-2, start ------*/

	// platform limited
	function newLuckCaptcha($luck_id, $user_id, $product_id, $main_type, $platform){/*{{{*/
		$luck_id = intval($luck_id);
		$user_id = intval($user_id);
		$product_id = intval($product_id);
		$main_type = trim($main_type);
		$platform = strval(trim($platform));
		if ($luck_id <= 0 || $user_id <= 0 || $product_id <= 0 || empty($main_type) || empty($platform)){
			return false;
		}

		if(!($platform_code = $this->platform_map($platform, true))){
			error_log("[Error]Platform map error: $platform", 0);
			return false;
		}

		$try_max_num = 4;  // 最多冲突次数+1
		 
		do{
			$captcha = $this->genCaptcha(4, 4);
			if (empty($captcha)){
				error_log("[Error]genCaptcha fail: $user_id, $product_id, $main_type, $platform", 0);
				return false;
			}

			$captcha = $platform_code . $captcha;
			$sql = sprintf("insert into g_luckcaptcha(luck_id, user_id, product_id, main_type, platform, code, status, create_time, user_name, phone, birthday, address, zipcode, province, city) select %d , %d, %d, '%s', '%s', '%s', '%s', '%s', u.g_realname, u.g_phone, u.g_birthday, u.g_address, u.g_zipcode, u.g_province, u.g_city from g_users as u where u.g_id= %d",
				$luck_id, $user_id, $product_id, mysql_real_escape_string($main_type),
				mysql_real_escape_string($platform), mysql_real_escape_string($captcha), 'pre',
				date("Y-m-d H:i:s"), intval($user_id)
			);
			$this->query($sql);
		} while($this->getAffectedRows() !== 1 && --$try_max_num > 0);

		if ($try_max_num <= 0){
			error_log("[Error]Complict for {$try_max_num} numbers!", 0);
			return false;
		}
		return $captcha;
	}/*}}}*/

	// platform limited
	function saveUinfoAndActive($code, $user_name, $phone, $birthday, $address, $zipcode, $province, $city, $status='active'){/*{{{*/
		$sql = sprintf("update g_luckcaptcha set user_name = '%s', birthday = '%s', phone = '%s', address = '%s', zipcode = '%s', province = '%s', city = '%s', status = '%s' where code = '%s'",
			mysql_real_escape_string($user_name),
			mysql_real_escape_string($birthday),
			mysql_real_escape_string($phone),
			mysql_real_escape_string($address),
			mysql_real_escape_string($zipcode),
			mysql_real_escape_string($province),
			mysql_real_escape_string($city),
			mysql_real_escape_string($status),
			mysql_real_escape_string($code)
		);
		$this->query($sql);
		return $this->getAffectedRows();
	}/*}}}*/

	// platform unlimited
	function getCaptchaUinfo($captcha, $status, $platform=null){/*{{{*/
		if (empty($captcha)){
			return false;
		}

		if ('taobao' == $platform){
			$url = 'http://i.try8.info/admin/direct/captcha.php?action=check_captcha&captcha='.$captcha;
			$json = $this->get_http_result($url);
			if (empty($json) || !($ret = json_decode($json, true))){
				return false;
			}
			if ($ret['Result'] != 1){
				return false;
			}
			$info = $ret['Msg'];
		} else if ('catpcha' == $platform){
			$database_name = $this->platform_db_map($platform);
			$info = $this->getCaptchaUinfoBg($captcha, $status, $database_name);
		} else {
			$database_name = $this->platform_db_map($platform);
			if (empty($database_name)){
				return false;
			}
			 
			$sql = sprintf("select c.id as cid, c.user_id, c.user_name as real_name, c.phone, 
				c.code, c.product_id, c.create_time, c.luck_id, c.birthday, c.address, c.zipcode, c.province, c.city,
				u.g_name as name, p.g_name as product_name
				from $database_name.g_luckcaptcha as c join $database_name.g_users as u on (c.user_id = u.g_id)
				join $database_name.g_products as p on(c.product_id = p.g_id)
				where c.code = '%s' and status = '%s' limit 1",
				mysql_real_escape_string($captcha),
				mysql_real_escape_string($status)
				);

			$ret = $this->query($sql);
			if (empty($ret)){
				return false;
			}
			$info = array();
			foreach($ret[0] as $table=>$row){
				$info = array_merge($info, $row); 
			}
		}
		return $info;

	}/*}}}*/

	function get_http_result($url) {/*{{{*/
		if (empty($url)){
			return false;
		}
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, "$url");
		curl_setopt($ch, CURLOPT_TIMEOUT, 8);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		$result = curl_exec($ch);
		$info = curl_getinfo($ch);


		curl_close($ch);

		if( $info['http_code'] != 200 )
			return '';

		return $result;
	}/*}}}*/

	// platform unlimited
	function updateCaptchaStatus($captcha_id, $status, $platform=null){/*{{{*/
		$database_name = $this->platform_db_map($platform);
		if (empty($database_name)){
			return false;
		}

		$sql = sprintf("update $database_name.g_luckcaptcha set status = '%s', apply_time=now() where id = %d",
			mysql_real_escape_string($status), intval($captcha_id)
		);

		$this->query($sql);
		return ($this->getAffectedRows() === 1);
	}/*}}}*/

	// platform unlimited
	function updateLuckStatus($user_id, $luck_id, $is_get, $platform=null){/*{{{*/
		if ($user_id <= 0 || $luck_id <= 0 || empty($is_get)){
			return false;
		}
		$database_name = $this->platform_db_map($platform);
		if (empty($database_name)){
			return false;
		}

		$sql = sprintf("update $database_name.g_lucks set is_get='%s' where uid=%d and seqid=%d",
			mysql_real_escape_string($is_get),
			intval($user_id),
			intval($luck_id)
		);
		$this->query($sql);
		return ($this->getAffectedRows() === 1);
	}/*}}}*/

	function updateCaptchaStatusBg($luck_id, $captcha, $platform){/*{{{*/
		$database_name = $this->platform_db_map($platform);
		$sql = sprintf("update $database_name.g_luckcaptcha set status = 'used', apply_time = now() where luck_id = %d and code = '%s'",
			intval($luck_id), mysql_real_escape_string($captcha)
		);
		$this->query($sql);
		return ($this->getAffectedRows() === 1);
	}/*}}}*/

	function getOrcheckCaptchaUrl($store, $token=null){/*{{{*/
		$secret_key = 'sf6556#$#l';
		$ok_token = md5($secret_key.$store);

		if (empty($token)){ // Get
			return "http://{$_SERVER['HTTP_HOST']}/product/checkCaptcha/{$store}/{$ok_token}/";
		} else { // Check
			return ($ok_token == $token);
		}
	}/*}}}*/

	function update_taobao_captcha($award_id, $captcha){/*{{{*/
		$url = "http://i.try8.info/admin/direct/captcha.php?action=update_captcha&captcha={$captcha}&cid={$award_id}";
		$json = $this->get_http_result($url);
		if (empty($json) || !($ret = json_decode($json, true))){
			echo "修改失败！";exit;
		}
		echo $ret['Msg']; exit;
	}/*}}}*/

	function getCaptchaUinfoBg($captcha, $status, $database_name){/*{{{*/
		$sql = sprintf("select c.id as cid, c.user_id as name, c.user_name as real_name, c.phone, 
			c.code, c.product_name, c.create_time, c.luck_id, c.birthday, c.address, c.zipcode, c.province, c.city
			from $database_name.g_luckcaptcha as c 
			where c.code = '%s' and status = '%s' limit 1",
			mysql_real_escape_string($captcha),
			mysql_real_escape_string($status)
		);

		$ret = $this->query($sql);
		if (empty($ret)){
			return false;
		}
		$info = array();
		foreach($ret[0] as $table=>$row){
			$info = array_merge($info, $row); 
		}
		return $info;
	}/*}}}*/

	// order: true-encode, false-decode
	function platform_map($platform, $order){/*{{{*/
		$map = array(
			'sina' => 'sn',
			'renren' => 'rr',
			'yoka' => 'yk',
			'myspace' => 'ms',
			'taobao' => 'tb',
			'catpcha' => 'bg',
		);

		if (!$order){
			$map = array_flip($map);
		}

		if (empty($map[$platform])){
			return false;
		}
		return $map[$platform];
	}/*}}}*/

	function platform_db_map($platform=null){/*{{{*/
		if (empty($platform)){
			$platform = SystemProperties::$platform;
		}
		$map = array(
			'sina' => 'tryapp_s',
			'renren' => 'tryapp_r',
			'yoka' => 'tryapp_y',
			'myspace' => 'tryapp_m',
			'catpcha' => 'catpcha',
		);

		return ((empty($map[$platform]))? null: $map[$platform]);
	}/*}}}*/

	// Only generate code with littel alpha and number
	function genCaptcha($alpha_len, $num_len){/*{{{*/
		if ($alpha_len <= 0 && $num_len <= 0){
			return null;
		}
		$alpha_pool = 'qwertyuiopasdfghjklzxcvbnm';
		$number_pool = '0123456789';
		$alpha_pool_len = strlen($alpha_pool)-1;
		$number_pool_len = strlen($number_pool)-1;

		$captcha = '';
		if ($alpha_len > 0){
			for($i=0; $i<$alpha_len; ++$i){
				$captcha .= $alpha_pool[mt_rand(0, $alpha_pool_len)];
			}
		}
		if ($num_len > 0){
			for($i=0; $i<$num_len; ++$i){
				$captcha .= $number_pool[mt_rand(0, $number_pool_len)];
			}
		}

		return $captcha;
	}/*}}}*/

	/*----- cy add, 2011-4-2,  end ------*/


	/*----- cy add, 2011-5-16, start ----*/
	function check_and_update_third_captcha($code, $user_id, $base_count, $inc_count, $user_platform, $group_name){/*{{{*/
		$sql = sprintf("update tryapp_s.g_thirdcaptcha set `count`=`count`+%d, user_id =%d, user_platform = '%s' where code ='%s' and `count`=%d and group_name = '%s'",
			intval($inc_count),
			intval($user_id),
			mysql_real_escape_string($user_platform),
			mysql_real_escape_string($code),
			intval($base_count)	,
			mysql_real_escape_string($group_name)
		);
		$this->query($sql);
		return ($this->getAffectedRows() === 1);
	}/*}}}*/
	/*----- cy add, 2011-5-16, end   ----*/

	/*----- cy add, 2011-6-30, start ----*/
	function fanli_list($page, $per_page, $platform){/*{{{*/
		$url = sprintf("http://i.try8.info/tshare/direct/ri.php?action=fanli_list&platform=%s&page=%d&per_page=%d", $platform, $page, $per_page);

		$ret = $this->get_http_result($url);
		if (empty($ret)){
			error_log("[Error]Empty from $url", 0);
			return false;
		}
		if(!($json = json_decode($ret, true))){
			error_log("[Error]Json decode fail from $url, $ret", 0);
			return false;
		}

		if ($json['Result'] != 1){
			error_log("[Error]Json Result fail from $url, {$json['Msg']}", 0);
			return false;
		}
		return $json['Msg'];
	}/*}}}*/

	function fanli_list_WithCache($page, $per_page, $platform){/*{{{*/
		$key = md5($page.'_'.$per_page.'_'.$platform);
		if ($ret = Cache::read($key, 'fanli_may_flush')) {
			return $ret;
		}
		$ret = $this->fanli_list($page, $per_page, $platform);
		Cache::write($key, $ret, 'fanli_may_flush');
		return $ret;
	}/*}}}*/
	/*----- cy add, 2011-6-30, end   ----*/
}
